package com.caifu.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author tianwenwen
 * ClassName: ImageUpload.java
 * version: 1.0.0
 * createTime: 2020年08月28日 14:14:19
 **/
public class ImageUpload {
    public static String imageSingleUpload(MultipartFile file, String fileUploadPath, String imageUrlPath) throws Exception {

        //获取文件上传名
        //String filename = file.getOriginalFilename();
        String filename = System.currentTimeMillis()+ ".jpg";
        //文件上传路径
        String fileUploadPathStr = fileUploadPath + File.separator + filename;
        File uploadFile = new File(fileUploadPathStr);
        //文件不存在创建
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        //压缩上传
        Thumbnails.of(file.getInputStream()).scale(0.3f).outputQuality(0.3f).toFile(fileUploadPathStr);
        //file.transferTo(uploadFile);
        //文件访问路径
        String imageUrl = imageUrlPath + filename;
        System.out.println("imageUrl = " + imageUrl);
        return imageUrl;

    }

    /**
     * 网络图片转二进制
     * @param imagePath
     * @return
     * @throws Exception
     */
    public static byte[] image2Bytes(String imagePath) throws Exception {
        URL url = new URL(imagePath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
        byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
        return btImg;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }



    public static void main(String[] args) throws Exception {
        String str = "http://140.207.2.182:6038/projectImage/user/20191119161809.jpg";
        byte[] bates = image2Bytes(str);
        String bTemp = "";
        if(bates != null){
            BASE64Encoder ecoder = new BASE64Encoder();
            bTemp = ecoder.encode(bates);
            bTemp = bTemp.replaceAll("[\\s*\t\n\r]", "");
            System.out.println(bTemp);
        }
    }

}
